﻿using Admin.Core.Common.Auth;
using Admin.Core.Common.Input;
using Admin.Core.Common.Output;
using Admin.Core.Model.Admin;
using Admin.Core.Repository.Admin.Tenant;
using Admin.Core.Repository.Admin.UserTenant;
using Admin.Core.Service.Admin.Tenant.Input;
using Admin.Core.Service.Admin.Tenant.Output;
using AutoMapper;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace Admin.Core.Service.Admin.Tenant
{
    public class TenantService : ITenantService
    {

        private readonly IUser _user;
        private readonly IMapper _mapper;
        private readonly ITenantRepository _tenantRepository;
        private readonly IUserTenantRepository _userTenantRepository;
        public TenantService(
            IUser user,
            IMapper mapper,
            ITenantRepository tenantRepository,
            IUserTenantRepository userTenantRepository
        )
        {
            _user = user;
            _mapper = mapper;
            _tenantRepository = tenantRepository;
            _userTenantRepository = userTenantRepository;
        }


        public async Task<IResponseOutput> PageAsync(PageInput<TenantEntity> input)
        {
            var key = input.Filter?.Name;

            var list = await _tenantRepository.Select
            .WhereIf(key.NotNull(), a => a.Name.Contains(key))
            .Count(out var total)
            .OrderByDescending(true, c => c.Id)
            .Page(input.CurrentPage, input.PageSize)
            .ToListAsync<TenantListOutput>();

            var data = new PageOutput<TenantListOutput>()
            {
                List = list,
                Total = total
            };

            return ResponseOutput.Ok(data);
        }

        

        public async Task<IResponseOutput> GetTenansAsync(string code)
        {
            var list = await _userTenantRepository.Select
            .InnerJoin<UserEntity>((a,b)=>(a.User.UserName == code || a.User.DomainAccName==code )&& a.UserId == b.Id)
            //.WhereIf(code.NotNull(), a => a.User.Contains(key))
            .Count(out var total)
            //.OrderByDescending(true, c => c.Id)
            //.Page(input.CurrentPage, input.PageSize)
            .ToListAsync(a => a.Tenant);

            var data = new PageOutput<TenantListOutput>()
            {
                List = _mapper.Map<List<TenantListOutput>>(list),
                Total = total
            };

            return ResponseOutput.Ok(data);
        }
        public async Task<IResponseOutput> GetAsync(long id)
        {
            var result = await _tenantRepository.GetAsync<TenantGetOutput>(id);
            return ResponseOutput.Ok(result);
        }



        public async Task<IResponseOutput> AddAsync(TenantAddInput input)
        {
            var entity = _mapper.Map<TenantEntity>(input);
            var id = (await _tenantRepository.InsertAsync(entity)).Id;

            return ResponseOutput.Result(id > 0);
        }

    }
}
